package core.util;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.mail.internet.MimeUtility;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
 * 
 * @author qiwx
 *
 */
public class EmailSend {
   
  private static Logger log = Logger.getLogger(EmailSend.class);
  private static PropertyUtil emailInfo ;
  private static String password = null;
  private static String emailFrom = "";
  private static String emailTo = "";// 发送
  private static String emailsmtp = "";
  private static String emailCopyTo = "";// 抄送
  private static String emailHiddenTo = "";// 暗送
  static{
    try {
      emailInfo = PropertyUtil.getInstance();
      password  = emailInfo.getValueByKey("email.password", "email");
      emailFrom = emailInfo.getValueByKey("email.from", "email");
      //emailTo   = emailInfo.getValueByKey("email.sendToEmailUsers", "email");
      emailsmtp = emailInfo.getValueByKey("email.smtp", "email");
      //emailCopyTo = emailInfo.getValueByKey("email.copyto", "email");
      //emailHiddenTo = emailInfo.getValueByKey("email.hiddento", "email");
   } catch (Exception e) {
    log.error("文件不存在：", (Throwable)e);
   } 
  }
  /**
   * 发送邮件
   * @param toWhom 收件人
   * @param subject 主题
   * @param mailbody  邮件主体
   * @param attachMentPath  附件
   * @param imgMap
   */
  public static void sendMail(String toWhom, String subject, String mailbody, List<String> attachMentPath,Map<String,String> imgMap) {
    emailTo = toWhom;
    sendMail( subject,  mailbody,  attachMentPath, imgMap);
  }

  /**
   * 发送邮件
   * @param subject 主题
   * @param mailbody  邮件主体
   * @param attachMentPath  附件
   * @param imgMap
   */
  public static void sendMail(String subject, String mailbody, List<String> attachMentPath,Map<String,String> imgMap) {
    try {
      send(subject, mailbody, attachMentPath, imgMap);
    } catch (Exception e) {
      log.error("send email error", e);
    }
  }
  
  public static boolean isNotNull( String str ) {
    if ( str == null || str.length() == 0) {
      return false;
    }
    return true;
  }
  
  public static boolean isNotNullList( List<?> list ) {
    if ( list == null || list.size() == 0 ) {
      return false;
    }
    return true;
  }
  
  public static boolean isNotNullMap(Map<?,?> map) {
    if ( map == null || map.size() == 0) {
      return false;
    }
    return true;
  }
  
  /**
   * 发送邮件含附件
   * @param subject 主题
   * @param mailbody 内容
   * @param filepathList 附件的路径
   * @param map 图片文件集合, key-value格式为<描述, 图片路径>
   * @throws Exception
   */
  public static void send(String subject, String mailbody, 
                                        List<String> filepathList,Map<String,String> imgMap)
                                                                              throws Exception {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(emailsmtp);
    email.setSmtpPort(25);
    email.setAuthentication(emailFrom, password);
    if (isNotNull(emailTo) && emailTo.contains(",")) {
      for (String toAddress : emailTo.split(",")) {
        email.addTo(toAddress);
      }
    } else if (isNotNull(emailTo)){
      email.addTo(emailTo);
    }
    if (isNotNull(emailCopyTo) && emailCopyTo.contains(",")) {
      for (String copyToAddress : emailCopyTo.split(",")) {
        email.addCc(copyToAddress);
      }
    } else if (isNotNull(emailCopyTo)){
      email.addCc(emailCopyTo);
    }
    if (isNotNull(emailHiddenTo) && emailHiddenTo.contains(",")) {
      for (String hiddenToAddress : emailHiddenTo.split(",")) {
        email.addBcc(hiddenToAddress);
      }
    } else if (isNotNull(emailHiddenTo)){
      email.addBcc(emailHiddenTo);
    }
    if ( isNotNullList(filepathList)) {
      for ( int i=0; i<filepathList.size(); i++ ) {
        EmailAttachment attachment = new EmailAttachment();
        String aName = filepathList.get(i);
        File f = new File( aName );
        if ( f.exists() ) {
          String realName = aName.substring(aName.lastIndexOf("\\") + 1);
          attachment.setPath(aName);
          attachment.setName(MimeUtility.encodeText(realName, "UTF-8","B"));
          attachment.setDisposition(EmailAttachment.ATTACHMENT);
          email.attach(attachment);
        }
      }
    }
    email.setFrom(emailFrom);
    // 设置标题的字符集
    email.setCharset("UTF-8");
    email.setSubject(subject);
    StringBuffer msg = new StringBuffer();
    msg.append("<html><body>");
    msg.append(mailbody);
    msg.append("<br>");
    if ( isNotNullMap(imgMap)) {
      Set set = imgMap.entrySet();
      Iterator it = set.iterator();
      while(it.hasNext()){
        Map.Entry<String, String> m = (Entry<String, String>) it.next();
        msg.append(m.getKey());
        msg.append("<br>");
        if( isNotNull(m.getValue()) ){
          File url = new File(m.getValue());// 将附件中的图片用于正文中
          msg.append("<img src=cid:").append(email.embed(url)).append(">");
          msg.append("<p>");
        }
      }
    }
    msg.append("</body></html>");
    email.setHtmlMsg(msg.toString());
    log.info("邮件发送中...");
    log.info("emailTo:"+emailTo);
    log.info("emailCopyTo:"+emailCopyTo);
    //log.info("mailbody:"+mailbody);
    try{
      String dd = email.send();
      log.info("发送成功！" + dd);
    }catch(Exception e){
      log.error("发送失败！", e);
      //log.info("1分钟后尝试重新发送\n");
      log.error("emailTo Error:"+emailTo);
      /*for ( int i=0; i<10; i++ ) {
        try {
          Thread.sleep(60000);
          String d = email.send();
          log.info("发送成功！" + d);
          return;
        } catch (Exception e1) {
          log.error("第"+ (i+1) +"次尝试重新发送失败, 1分钟后重新发送\n", e);
        }
      }*/
    }
  }
  
  public static void main(String[] args) {
    StringBuffer  mainBody = 
    new StringBuffer("<div id='top' class='div_top'>");
    mainBody.append("群发邮件测试");
    mainBody.append("</div>");
    String mails = "yuyuef@yonyou.com";
    		//"huangj@yonyou.com,yjm@yonyou.com,zwh@yonyou.com,gcwx@yonyou.com,liuyingm@yonyou.com,yangkaic@yonyou.com,wl170@yonyou.com,yuyuef@yonyou.com,qfx@yonyou.com,xingzhic@yonyou.com,chenlei1@yonyou.com,weidong@yonyou.com,zhangleic@yonyou.com,wy@yonyou.com,tianyuanb@yonyou.com";
    EmailSend.sendMail(mails,"邮件群发测试", mainBody.toString(), null, null);
  }
}
